from osgeo import gdal
import os
import numpy as np
import time
from modis_utils import *
import warnings
warnings.filterwarnings(action='ignore')


def merge_tiff(tiff_list, output_dir, fill):
    min_x, max_y, max_x, min_y = get_extent(tiff_list[0])
    for in_fn in tiff_list[1:]:
        minx, maxy, maxx, miny = get_extent(in_fn)
        min_x = min(min_x, minx)
        min_y = min(min_y, miny)
        max_x = max(max_x, maxx)
        max_y = max(max_y, maxy)
    in_ds = gdal.Open(tiff_list[0])
    geotrans = list(in_ds.GetGeoTransform())
    geotrans = [min_x, geotrans[1], 0, max_y, 0, geotrans[5]]
    xsize = int((max_x - min_x) / geotrans[1] + 0.5)
    ysize = int((min_y - max_y) / geotrans[5] + 0.5)
    # band_type = in_ds.GetRasterBand(1).DataType
    driver = gdal.GetDriverByName('GTiff')
    out_ds = driver.Create(output_dir, xsize, ysize, 1, gdal.GDT_Float32)
    # fill = float(in_ds.GetMetadata()['_FillValue'])
    out_ds.SetGeoTransform(geotrans)
    out_ds.SetProjection(in_ds.GetProjection())
    out_ds.GetRasterBand(1).SetNoDataValue(fill)
    out_ds.GetRasterBand(1).Fill(fill)
    for in_fns in tiff_list:
        print(in_fns)
        in_ds = gdal.Open(in_fns)
        copy_into(out_ds, in_ds, 1, 1, fill)


if __name__ == '__main__':
    output_path = 'F:/16satellite/data/gongpeng/new'
    input_path = 'F:/16satellite/data/gongpeng/new/conver'
    tiff_list = find_layers_files(input_path, '.tif')
    print(tiff_list)
    output_tiff_dir = output_path + '/2010_global.tif'
    if os.path.exists(output_tiff_dir):
        os.remove(output_tiff_dir)
        print('{} tiff file is exist and remove'.format(output_tiff_dir))
    merge_tiff(tiff_list, output_tiff_dir, 0)

